/**
 *
 */
package com.ssyt.examinationsystem.dao.impl;

import com.jdbc.util.JdbcUtils;
import com.ssyt.examinationsystem.dao.IBlankInfoDAO;
import com.ssyt.examinationsystem.entity.BlankInfo;
import com.ssyt.examinationsystem.entity.PageBean;
import com.ssyt.examinationsystem.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author Long.
 * @version 1.0
 * @className BlankInfoDAOImpl
 * @since 2016年10月30日
 */
public class BlankInfoDAOImpl implements IBlankInfoDAO {

    @Override
    public int addBlankInfo(BlankInfo blank) {
        String sql = "insert into blankinfo values(null,?,?,?)";
        Object[] parameters = {blank.getQuestion(), blank.getAnswer(), blank.getCourse().getCourseId()

        };
        return JdbcUtils.executeUpdate(sql, parameters);
    }

    @Override
    public List<Map<String, Object>> getBlank() {

        return JdbcUtils.executeQuery("select * from blankinfo");
    }

    @Override
    public int updateBlank(BlankInfo blank) {
        String sql = "update blankinfo set question=?,answer=?,courseid=? where blankId=?";
        Object[] parameters = {blank.getQuestion(), blank.getAnswer(), blank.getCourse().getCourseId(),
                blank.getBlankId()};
        return JdbcUtils.executeUpdate(sql, parameters);
    }

    @Override
    public int deleteBlank(String blankId) {
        return JdbcUtils.executeUpdate("delelte from blankinfo where blankid=?", blankId);
    }

    @Override
    public List<Map<String, Object>> getBlankByPage(PageBean page) {
        String sql = "select * from blankinfo limit ?,?";
        // 获取每页显示记录数，当前页
        Integer pageSize = page.getPageSize();
        Integer currentPage = page.getCurrentPage();
        // 计算每页显示第一条记录索引
        Integer startIndex = (currentPage - 1) * pageSize;

        Object[] parameters = {startIndex, pageSize};
        return JdbcUtils.executeQuery(sql, parameters);
    }

    @Override
    public int getTotalCount() {
        String sql = "select * from blankinfo";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql);
        return CollectionUtils.isEmptyForList(list) ? list.size() : 0;
    }

    @Override
    public Map<String, Object> getBlankInfoById(String blankId, String courseId) {
        String sql = "select * from blankInfo where blankId= ? and courseId = ?";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql, blankId, courseId);

        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<Map<String, Object>> getRandomBlankInfoById(String number, String courseId) {
        String sql = "select * from blankInfo where courseId=? order by rand() limit ?";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql, courseId, Integer.parseInt(number));

        return list;
    }

}
